<!doctype html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
        }

        section {
            display: flex;
            align-items: center;
            justify-content: center;
            line-height: 1;
            height: 300px;
            font-size: 36px;
            color: #fff;
        }

        section.active h2 {
            color: #000;
        }

        #section-1 {
            background: #4286F5;
        }

        #section-2 {
            background: #EA4235;
        }

        #section-3 {
            background: #FABC05;
        }

        #section-4 {
            background: #34A853;
        }
    </style>
</head>
<body>

<section id="section-1">
    <h2>区域一</h2>
</section>

<section id="section-2">
    <h2>区域二</h2>
</section>

<section id="section-3">
    <h2>区域三</h2>
</section>

<section id="section-4">
    <h2>区域四</h2>
</section>

<script>
    const dzObserver = new IntersectionObserver(entries => {
        entries.forEach(function (entry) {
            if (entry.isIntersecting) {
                entry.target.classList.add('active');
            } else {
                entry.target.classList.remove('active');
            }
        });
    }, {
        rootMargin: '-50% 0% -50% 0%'
    });

    document.querySelectorAll('section').forEach(element => {
        dzObserver.observe(element)
    })
</script>

</body>
</html>
